const express = require('express');
const app = express();
const cors = require('cors');
const session = require('express-session');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

//https
const fs = require('fs');
const path = require('path');
const https = require('https');
let privateKey  = fs.readFileSync(path.join(__dirname, './credentials/private.pem'), 'utf8');
let certificate = fs.readFileSync(path.join(__dirname, './credentials/file.crt'), 'utf8');
let credentials = {key: privateKey, cert: certificate};
const httpsServer = https.createServer(credentials, app);
httpsServer.listen(8848, function() {
    console.log('HTTPS Server is running on: https://localhost:8848');
});

app.use(bodyParser.json()); // for parsing application/json
app.use(session({
    secret:'secret',
    resave:true,
    saveUninitialized:false,
    cookie:{
        path:'/',
        httpOnly:true,
        maxAge:1000 * 60 * 1,
    },
}));

app.use(cors({origin:'http://localhost:8080',credentials:true}));
app.use(cookieParser("localhost"));
// app.use(bodyParser.json({ type: 'application/*+json' }));

//const serveStatic = require('serve-static');
//app.use(express.static('./public'));

//handler
let {postImgHandler} = require('./routers/postImgHandler');
let {findAllFiles} = require('./utils/fileFinder') ;
let {handleLogin} = require('./routers/loginHandler');

//define constant
let LISTEN_PORT = 8849;
let ROUTE_INDEX = '/';
let ROUTE_POST_IMG = '/post/img';
let ROUTE_GET_IMG = '/get/img';
let USER_LOGIN = '/login';

//routers
app.get(ROUTE_INDEX,(req,res)=>res.send('Hello World!'));
app.post(ROUTE_POST_IMG,(req,res)=>postImgHandler(req,res));
app.get(ROUTE_GET_IMG,(req,res)=>findAllFiles(req));//TODO
app.post(USER_LOGIN,(req,res)=>handleLogin(req,res));

app.listen(LISTEN_PORT,()=>console.log('Listening!'));
